#!/sbin/sh

set -e

interface="${1}"
updater_fd="${2}"
zipfile="${3}"

ui_print() {
    echo -en "ui_print ${1}\n" > /proc/self/fd/"${updater_fd}"
    echo -en "ui_print\n" > /proc/self/fd/"${updater_fd}"
}

mount /system || :
mount /cache || :
mount /data || :

rm -rf /tmp/dbu/
mkdir -p /tmp/dbu/
cd /tmp/dbu/

unzip "${zipfile}"

cat > utilities_cmd.sh <<EOF
#!/sbin/sh
/tmp/dbu/mbtool utilities --device /tmp/dbu/devices.json "\${@}"
EOF

chmod 755 utilities_cmd.sh mbtool

ui_print "Generating AROMA config based on installed ROMS"
./utilities_cmd.sh generate /tmp/dbu/template /tmp/dbu/aroma.zip

ui_print "Starting AROMA"
chmod 755 template/META-INF/com/google/android/update-binary
exec template/META-INF/com/google/android/update-binary \
    "${interface}" "${updater_fd}" aroma.zip
